package com.neusoft.service.impl;

import com.neusoft.dao.UserDao;
import com.neusoft.dao.impl.UserDaoImpl;
import com.neusoft.db.DBManager;
import com.neusoft.model.User;
import com.neusoft.service.UserService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDaoImpl userDao = new UserDaoImpl();
    private Connection conn = null;

    @Override
    public User isValidateLogin(String username, String password) {
        DBManager dbManager = DBManager.getInstance();
        conn = dbManager.getConnection();//连接数据库
        //注入数据库连接
        userDao.setConnection(conn);
        //调用dao层的方法
        User user = userDao.login(username,password);
        return user;
    }



    @Override
    public boolean saveUser(User user) {
        boolean isRight = false;
        try {
            DBManager dbManager = DBManager.getInstance();
            conn = dbManager.getConnection();//连接数据库
            //注入数据库连接
            userDao.setConnection(conn);
            isRight = userDao.register(user); //调用dao层的方法
            //如果添加成功就需要提交事务
            conn.commit(); //手动提交事务
        } catch (SQLException e) {
            try {
                //否则就要回滚，取消之前所有的操作
                conn.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        return isRight;
    }

    @Override
    public List<User> getUsers() {
        DBManager dbManager = DBManager.getInstance();
        conn = dbManager.getConnection();//连接数据库
        //注入数据库连接
        userDao.setConnection(conn);
        List<User> users = userDao.getUsers();
        return users;
    }

    @Override
    public User findUserById(int id) {
        DBManager dbManager = DBManager.getInstance();
        conn = dbManager.getConnection();//连接数据库
        //注入数据库连接
        userDao.setConnection(conn);
        User user = userDao.findUserById(id);
        return user;
    }

    @Override
    public boolean updateUser(User user) {
        return false;
    }

    @Override
    public boolean deleteUser(int id) {
        boolean isRight = false;
        try {
            DBManager dbManager = DBManager.getInstance();
            conn = dbManager.getConnection();//连接数据库
            //注入数据库连接
            userDao.setConnection(conn);
            isRight = userDao.deleteUser(id);
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        return isRight;
    }




}
